﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Xfm.Core.Auth
{
    /// <summary>
    /// 简单权限没什么好扩展的，已经很简单了。
    /// </summary>
    public static class XfAuthExtention
    {
        /// <summary>
        /// 简化登陆Claim拼接
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="user"></param>
        /// <param name="roleName"></param>
        /// <param name="otherClaims"></param>
        /// <returns></returns>
        public static async Task XfmSignInAsync(this HttpContext httpContext, BaseUser user, string roleName, IEnumerable<Claim> otherClaims = null)
        {
            if (user == null)
                throw new ArgumentNullException("用户为null");
            if (string.IsNullOrEmpty(user.UserName))
                throw new ArgumentNullException("用户名不能为空");
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.Integer, null));
            claims.Add(new Claim(ClaimTypes.Name, user.UserName, ClaimValueTypes.String, null));
            if (!string.IsNullOrEmpty(roleName))
                claims.Add(new Claim(ClaimTypes.Role, roleName, ClaimValueTypes.String, null));
            if (otherClaims != null)
                claims.AddRange(otherClaims);
            await httpContext.XfmSignInAsync(claims);
        }
        /// <summary>
        /// Xfm扩展登录，自定义的Claim集合
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="claims">Claim集合</param>
        /// <returns></returns>
        public static async Task XfmSignInAsync(this HttpContext httpContext, IEnumerable<Claim> claims)
        {
            var claimsPrincipal = new ClaimsPrincipal();
            var claimsIdentity = new ClaimsIdentity(claims);
            claimsPrincipal.AddIdentity(claimsIdentity);
            await httpContext.SignInAsync(claimsPrincipal);
        }
        public static async Task XfmSignOutAsync(this HttpContext httpContext)
        {
            await httpContext.SignOutAsync();
        }
    }
}
